//
//  IMAdStrategyManager.m
//  DualMediationSDK
//
//  广告策略管理器实现
//  Created by YeJary on 2025/7/15.
//

#import "IMAdStrategyManager.h"
#import "IMAdStrategyModels.h"
#import "IMSDKStartupConfigManager.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import "../../Utils/JSON/IMJSONUtils.h"

// 静态变量声明
static NSDictionary *_sceneNameMapping;
static NSDictionary *_sceneDescMapping;

// 字段常量定义
static NSString * const FIELD_AD_WAIT_TIME = @"ad_wait_time";
static NSString * const FIELD_AD_DAILY_LIMIT = @"ad_daily_limit";
static NSString * const FIELD_LAUNCH_TIMES = @"launch_times";
static NSString * const FIELD_AD_DAY_INTERVAL = @"ad_day_interval";
static NSString * const FIELD_AD_TIMES_INTERVAL = @"ad_times_interval";
static NSString * const FIELD_CUR_LEVEL = @"cur_level";
static NSString * const FIELD_AD_LEVEL_INTERVAL = @"ad_level_interval";
static NSString * const FIELD_AD_IMPRESSION_INTERVAL = @"ad_impression_interval";
static NSString * const FIELD_ONLINE_TIME = @"online_time";
static NSString * const FIELD_AD_MOB_FIRST = @"ad_mob_first";
static NSString * const FIELD_AD_BANNER_SHORT_SHOW = @"ad_banner_short_show";
static NSString * const FIELD_AD_IMPRESSION_POS = @"ad_impression_pos";

// SDK配置字段常量
static NSString * const FIELD_SDK_CONFIG_LOG = @"sdk_config_log";
static NSString * const FIELD_SDK_CONFIG_NEW_USER_DAY = @"sdk_config_new_user_day";
static NSString * const FIELD_SDK_CONFIG_USER_SWITCH = @"sdk_config_user_switch";
static NSString * const FIELD_SDK_CONFIG_US_PRIVACY = @"sdk_config_us_privacy";
static NSString * const FIELD_SDK_CONFIG_ADJUST_EVENT = @"sdk_config_adjust_event";
static NSString * const FIELD_SDK_CONFIG_SDK_TYPE = @"sdk_config_sdk_type";
static NSString * const FIELD_SDK_CONFIG_AD_TRACK = @"sdk_config_ad_track";
static NSString * const FIELD_SDK_CONFIG_AD_LOAD_TRACK = @"sdk_config_ad_load_track";
static NSString * const FIELD_SDK_CONFIG_FB_CTL = @"sdk_config_fb_ctl";
static NSString * const FIELD_SDK_CONFIG_FB_LEVEL_EVENT = @"sdk_config_fb_lv_event";

@interface IMAdStrategyManager ()

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, IMAdSceneStrategy *> *sceneStrategies;
@property (nonatomic, strong) NSMutableDictionary *adShowRecords; // 广告展示记录
@property (nonatomic, strong) NSMutableDictionary *userBehaviorData; // 用户行为数据
@property (nonatomic, assign) NSTimeInterval appInstallTime; // 应用安装时间
@property (nonatomic, assign) NSInteger appLaunchCount; // 应用启动次数

@end

@implementation IMAdStrategyManager

+ (instancetype)sharedManager {
    static IMAdStrategyManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[IMAdStrategyManager alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupSceneMappings];
        self.sceneStrategies = [NSMutableDictionary dictionary];
        self.adShowRecords = [NSMutableDictionary dictionary];
        self.userBehaviorData = [NSMutableDictionary dictionary];
        [self loadUserBehaviorData];
        [self initializeDefaultStrategies];
    }
    return self;
}

#pragma mark - 场景映射设置

- (void)setupSceneMappings {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sceneNameMapping = @{
            @"SCENE_SPLASH_COOL": @(IMAdSceneSplashCool),
            @"SCENE_SPLASH_HOT": @(IMAdSceneSplashHot),
            @"SCENE_BANNER_INIT": @(IMAdSceneBannerInit),
            @"SCENE_BANNER_LEVEL_ENTER": @(IMAdSceneBannerLevelEnter),
            @"SCENE_INTER_LEVEL_WIN": @(IMAdSceneInterLevelWin),
            @"SCENE_INTER_LEVEL_FAIL": @(IMAdSceneInterLevelFail),
            @"SCENE_INTER_LEVEL_RETRY": @(IMAdSceneInterLevelRetry),
            @"SCENE_INTER_LEVEL_WAIT": @(IMAdSceneInterLevelWait),
            @"SCENE_NATIVE_SETTLEMENT": @(IMAdSceneNativeSettlement),
            @"SCENE_SDK_CONFIG": @(IMAdSceneSDKConfig)
        };
        
        _sceneDescMapping = @{
            @(IMAdSceneOpenScreen): @"开屏场景-冷启动",
            @(IMAdSceneLevelStart): @"关卡开始",
            @(IMAdSceneLevelWin): @"关卡胜利",
            @(IMAdSceneLevelFail): @"关卡失败",
            @(IMAdSceneLevelRetry): @"关卡重试",
            @(IMAdSceneLevelWait): @"关卡等待提示",
            @(IMAdSceneNativeSettlement): @"原生结算界面",
            @(IMAdSceneBannerInit): @"banner场景-初始化",
            @(IMAdSceneBannerLevelEnter): @"banner场景-进入大厅",
            @(IMAdSceneInterLevelWin): @"插屏场景-关卡胜利",
            @(IMAdSceneInterLevelFail): @"插屏场景-关卡失败",
            @(IMAdSceneInterLevelRetry): @"插屏场景-关卡重试",
            @(IMAdSceneInterLevelWait): @"插屏场景-关卡等待提示",
            @(IMAdSceneNativeSettlement2): @"原生结算界面2",
            @(IMAdSceneSDKConfig): @"SDK配置场景"
        };
    });
}

+ (IMAdScene)sceneFromName:(NSString *)sceneName {
    NSNumber *sceneNumber = _sceneNameMapping[sceneName];
    return sceneNumber ? (IMAdScene)[sceneNumber integerValue] : IMAdSceneOpenScreen;
}

#pragma mark - 初始化

- (void)initializeAdStrategy {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 初始化广告策略"];
    
    // 注释：不再从本地配置文件加载策略，现在只依赖网络接口数据
    // 策略数据将通过updateStrategiesFromResponse:方法从网络接口获取并更新
    // [self loadStrategyFromConfig];
    
    // 初始化用户行为数据
    [self initializeUserBehaviorData];
    
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 广告策略初始化完成，当前策略数量: %lu (等待网络接口更新)", (unsigned long)self.sceneStrategies.count];
}

- (void)loadStrategyFromConfig {
    // 从本地JSON配置文件读取广告策略数据
    NSString *configPath = [[NSBundle mainBundle] pathForResource:@"sdk_config_mediation" ofType:@"json"];
    if (!configPath) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 配置文件不存在，使用默认策略"];
        return;
    }
    
    NSData *configData = [NSData dataWithContentsOfFile:configPath];
    if (!configData) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 配置文件读取失败，使用默认策略"];
        return;
    }
    
    NSError *error;
    NSDictionary *configDict = [NSJSONSerialization JSONObjectWithData:configData options:0 error:&error];
    if (error || !configDict) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 配置文件解析失败: %@，使用默认策略", error.localizedDescription];
        return;
    }
    
    // 解析广告策略配置
    NSDictionary *adStrategyConfig = configDict[@"ad_strategy_config"];
    if (!adStrategyConfig) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 配置文件中未找到广告策略配置，使用默认策略"];
        return;
    }
    
    // 解析场景策略配置
    if (adStrategyConfig) {
        NSArray *sceneConfigs = [IMJSONUtils safeArrayFromDictionary:adStrategyConfig forKey:@"scenes"];
        for (NSDictionary *sceneConfig in sceneConfigs) {
            IMAdSceneStrategy *strategy = [IMAdSceneStrategy sceneStrategyFromDictionary:sceneConfig];
            if (strategy) {
                // 根据scene_name映射到场景枚举
                IMAdScene scene = [IMAdStrategyManager sceneFromName:strategy.scene_name];
                self.sceneStrategies[@(scene)] = strategy;
                [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 加载场景策略: %@ - %@", strategy.scene_name, strategy.scene_desc];
            }
        }
    }
}

- (void)initializeDefaultStrategies {
    // 初始化默认策略
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 初始化默认策略"];
    
    // 构建默认的SDK启动配置策略，确保即使网络失败也能有有效配置
    IMSDKStartupConfig *defaultConfig = [self getDefaultSDKStartupConfig];
    NSDictionary *additional = [defaultConfig toDictionary];
    
    IMAdCondition *cond = [[IMAdCondition alloc] init];
    cond.additionalConditions = additional ?: @{};
    
    IMAdStrategy *strategy = [[IMAdStrategy alloc] init];
    strategy.strategy_id = @"DEFAULT_SDK_CONFIG";
    strategy.ad_status = 1; // 默认启用
    strategy.rate = 100;    // 100%命中
    strategy.ad_cond = cond;
    
    IMAdSceneStrategy *sceneStrategy = [[IMAdSceneStrategy alloc] init];
    sceneStrategy.scene_name = @"SCENE_SDK_CONFIG";
    sceneStrategy.scene_desc = @"默认SDK配置场景";
    sceneStrategy.country = @"ALL";
    sceneStrategy.user_type = 3; // 所有用户
    sceneStrategy.strategy = @[strategy];
    
    // 存储到场景策略映射
    self.sceneStrategies[@(IMAdSceneSDKConfig)] = sceneStrategy;
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 已初始化默认SDK配置场景策略，包含 %lu 个策略", (unsigned long)sceneStrategy.strategy.count];
}

- (void)loadUserBehaviorData {
    // 加载用户行为数据
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 加载用户行为数据"];
}

- (void)initializeUserBehaviorData {
    // 初始化用户行为数据
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 初始化用户行为数据"];
}

#pragma mark - 公共方法

- (nullable id)getConditionForScene:(IMAdScene)scene {
    // 由于IMAdStrategyModels.h中没有IMAdStrategyCondition类，这里返回nil
    // 实际应用中需要根据具体需求调整
    return nil;
}

- (nullable IMSDKStartupConfig *)getSDKStartupConfig {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 获取SDK启动配置"];
    
    // 调试日志：当前所有场景策略状态
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 当前策略状态调试 - 总策略数量: %lu", (unsigned long)self.sceneStrategies.count];
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 所有已加载的场景策略键: %@", self.sceneStrategies.allKeys];
    
    // 详细检查每个策略
    for (NSNumber *sceneKey in self.sceneStrategies.allKeys) {
        IMAdSceneStrategy *strategy = self.sceneStrategies[sceneKey];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 场景策略详情 - 键: %@, 场景名: %@, 策略对象: %@", sceneKey, strategy.scene_name, strategy ? @"存在" : @"不存在"];
    }
    
    // 特别检查SDK配置场景
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 SDK配置场景检查 - IMAdSceneSDKConfig枚举值: %ld", (long)IMAdSceneSDKConfig];
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 查找键 @(%ld) 是否存在于策略字典中", (long)IMAdSceneSDKConfig];
    
    // 获取SDK配置场景的策略数据
    IMAdSceneStrategy *sdkConfigStrategy = self.sceneStrategies[@(IMAdSceneSDKConfig)];
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 SDK配置策略获取结果: %@", sdkConfigStrategy ? @"成功" : @"失败(nil)"];
    
    if (!sdkConfigStrategy) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] ❌ 未找到SDK配置场景策略，使用默认配置"];
        
        // 容错处理：检查是否有策略数据但映射错误
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 容错检查 - 尝试遍历所有策略寻找SCENE_SDK_CONFIG"];
        for (NSNumber *sceneKey in self.sceneStrategies.allKeys) {
            IMAdSceneStrategy *strategy = self.sceneStrategies[sceneKey];
            if ([strategy.scene_name isEqualToString:@"SCENE_SDK_CONFIG"]) {
                [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 发现场景名匹配但键不匹配的策略 - 键: %@, 场景名: %@", sceneKey, strategy.scene_name];
                sdkConfigStrategy = strategy;
                break;
            }
        }
        
        if (!sdkConfigStrategy) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 容错检查也未找到SDK配置策略，使用默认配置"];
            IMSDKStartupConfig *defaultConfig = [self getDefaultSDKStartupConfig];
            // 自动应用默认配置
            [[IMSDKStartupConfigManager sharedManager] applySDKStartupConfig:defaultConfig];
            return defaultConfig;
        } else {
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ 通过容错检查找到SDK配置策略"];
        }
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 找到SDK配置场景策略，策略数量: %lu", (unsigned long)sdkConfigStrategy.strategy.count];
    
    // 从策略中提取配置参数
    NSMutableDictionary *configDict = [NSMutableDictionary dictionary];
    
    // 遍历策略列表，提取SDK配置参数
    for (NSInteger i = 0; i < sdkConfigStrategy.strategy.count; i++) {
        IMAdStrategy *strategy = sdkConfigStrategy.strategy[i];
        [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 处理策略 %ld: ad_cond=%@", (long)i, strategy.ad_cond ? @"存在" : @"不存在"];
        
        if (strategy.ad_cond && strategy.ad_cond.additionalConditions) {
            NSDictionary *additionalConditions = strategy.ad_cond.additionalConditions;
            [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 策略 %ld additionalConditions内容: %@", (long)i, additionalConditions];
            
            // 提取各种SDK配置参数
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_LOG toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_NEW_USER_DAY toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_USER_SWITCH toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_US_PRIVACY toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_ADJUST_EVENT toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_SDK_TYPE toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_AD_TRACK toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_AD_LOAD_TRACK toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_FB_CTL toDict:configDict];
            [self extractConfigValue:additionalConditions key:FIELD_SDK_CONFIG_FB_LEVEL_EVENT toDict:configDict];
        } else {
            [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 策略 %ld 缺少additionalConditions", (long)i];
        }
    }
    
    // 记录提取到的配置参数总结
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 配置参数提取完成，共提取到 %lu 个参数: %@", (unsigned long)configDict.count, configDict.allKeys];
    
    // 特别检查SDK_TYPE参数
    id sdkTypeValue = configDict[FIELD_SDK_CONFIG_SDK_TYPE];
    if (sdkTypeValue) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ SDK_TYPE参数已提取: %@", sdkTypeValue];
    } else {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] ❌ SDK_TYPE参数未提取到，将使用默认值"];
    }
    
    // 如果没有找到配置参数，使用默认配置
    if (configDict.count == 0) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] SDK配置场景中未找到配置参数，使用默认配置"];
        IMSDKStartupConfig *defaultConfig = [self getDefaultSDKStartupConfig];
        // 自动应用默认配置
        [[IMSDKStartupConfigManager sharedManager] applySDKStartupConfig:defaultConfig];
        return defaultConfig;
    }
    
    // 创建SDK启动配置实例
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔧 开始从字典创建SDK配置对象，字典内容: %@", configDict];
    IMSDKStartupConfig *config = [IMSDKStartupConfig configFromDictionary:configDict];
    
    if (config) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ SDK配置对象创建成功"];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 配置对象中sdk_config_sdk_type值: %@", config.sdk_config_sdk_type];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 配置对象中sdk_config_sdk_type类型: %@", [config.sdk_config_sdk_type class]];
    } else {
        [IMLogUtils error:IMLogTagGeneral format:@"[AdStrategyManager] ❌ SDK配置对象创建失败"];
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] SDK启动配置获取成功，最终sdk_config_sdk_type值: %@", config.sdk_config_sdk_type];
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 完整配置对象: %@", config];
    
    // 自动应用配置参数
    [[IMSDKStartupConfigManager sharedManager] applySDKStartupConfig:config];
    
    return config;
}

- (void)applySDKStartupConfiguration {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 手动应用SDK启动配置"];
    
    // 获取并应用SDK启动配置
    IMSDKStartupConfig *config = [self getSDKStartupConfig];
    if (config) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] SDK启动配置应用完成"];
    } else {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 未能获取SDK启动配置"];
    }
}

- (void)applySDKStartupConfig:(nullable IMSDKStartupConfig *)config {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 应用指定的SDK启动配置"];
    
    if (config) {
        // 使用配置管理器应用配置
        [[IMSDKStartupConfigManager sharedManager] applySDKStartupConfig:config];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 指定的SDK启动配置应用完成"];
    } else {
        // 应用默认配置
        [[IMSDKStartupConfigManager sharedManager] applyDefaultSDKStartupConfig];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 应用默认SDK启动配置完成"];
    }
}

- (void)updateAdShowRecord:(IMAdScene)scene {
    // 更新广告展示记录
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 更新广告展示记录: %ld", (long)scene];
}

- (void)reportLevelBehavior:(IMAdScene)scene
                      level:(NSInteger)level
                 onlineTime:(NSTimeInterval)onlineTime
                 completion:(void(^)(BOOL shouldShowAd, id _Nullable condition))completion {
    
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 上报关卡行为: scene=%ld, level=%ld, onlineTime=%.1f", 
     (long)scene, (long)level, onlineTime];
    
    // 检查是否应该展示广告
    BOOL shouldShow = [self shouldShowAdForScene:scene userLevel:level onlineTime:onlineTime];
    id condition = [self getConditionForScene:scene];
    
    if (completion) {
        completion(shouldShow, condition);
    }
}

- (BOOL)shouldShowAdForScene:(IMAdScene)scene
                   userLevel:(NSInteger)userLevel
                  onlineTime:(NSTimeInterval)onlineTime {
    // 先根据策略检查该场景是否被禁用
    if (![self isAdEnabledForScene:scene]) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 场景 %ld 的广告被策略(ad_status)禁用", (long)scene];
        return NO;
    }

    IMAdSceneStrategy *strategy = self.sceneStrategies[@(scene)];
    if (!strategy) {
        [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 未找到场景策略: %ld", (long)scene];
        // 无策略时不展示，保持保守
        return NO;
    }
    
    // TODO: 可在此补充更细的条件判断（如次数间隔、天间隔、关卡等）
    return YES;
}

- (BOOL)isAdEnabledForScene:(IMAdScene)scene {
    IMAdSceneStrategy *sceneStrategy = self.sceneStrategies[@(scene)];
    if (!sceneStrategy) {
        // 缺少策略时默认不禁用（由 shouldShowAdForScene 统一决定是否展示）
        return YES;
    }
    BOOL hasEnabled = NO;
    BOOL hasDisabled = NO;
    for (IMAdStrategy *st in sceneStrategy.strategy) {
        if (st.ad_status == 1) {
            hasEnabled = YES;
        } else if (st.ad_status == 0) {
            hasDisabled = YES;
        }
    }
    // 若存在开启策略则认为可用；否则若存在关闭策略则禁用；都没有则默认可用
    if (hasEnabled) return YES;
    if (hasDisabled) return NO;
    return YES;
}

- (void)updateAdShowRecord:(IMAdScene)scene level:(NSInteger)level {
    // 更新广告展示记录
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 更新广告展示记录: scene=%ld, level=%ld", (long)scene, (long)level];
}

#pragma mark - 私有方法

/**
 * 从条件字典中提取配置值
 * @param conditions 条件字典
 * @param key 配置键
 * @param configDict 目标配置字典
 */
- (void)extractConfigValue:(NSDictionary *)conditions key:(NSString *)key toDict:(NSMutableDictionary *)configDict {
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 尝试提取配置参数: %@, 条件字典包含 %lu 个键", key, (unsigned long)conditions.count];
    
    // 特别关注SDK_TYPE的提取过程
    if ([key isEqualToString:FIELD_SDK_CONFIG_SDK_TYPE]) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 正在提取关键参数 SDK_TYPE, 条件字典所有键: %@", conditions.allKeys];
    }
    
    id value = conditions[key];
    if (value) {
        configDict[key] = value;
        if ([key isEqualToString:FIELD_SDK_CONFIG_SDK_TYPE]) {
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ 成功提取SDK_TYPE配置参数: %@ = %@", key, value];
        } else {
            [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 提取配置参数: %@ = %@", key, value];
        }
    } else {
        if ([key isEqualToString:FIELD_SDK_CONFIG_SDK_TYPE]) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] ❌ 未找到SDK_TYPE配置参数，键 '%@' 在条件字典中不存在", key];
        } else {
            [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 未找到配置参数: %@", key];
        }
    }
}

/**
 * 获取默认SDK启动配置
 * @return 默认配置实例
 */
- (IMSDKStartupConfig *)getDefaultSDKStartupConfig {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 使用默认SDK启动配置"];
    
    NSDictionary *defaultConfig = @{
        FIELD_SDK_CONFIG_LOG: @(YES),                    // 默认开启日志
        FIELD_SDK_CONFIG_NEW_USER_DAY: @(7),            // 默认7天新用户
        FIELD_SDK_CONFIG_USER_SWITCH: @(YES),           // 默认开启用户分层
        FIELD_SDK_CONFIG_US_PRIVACY: @(NO),             // 默认关闭美国隐私弹窗
        FIELD_SDK_CONFIG_ADJUST_EVENT: @"",             // 默认无Adjust事件
        FIELD_SDK_CONFIG_SDK_TYPE: @"IS&MAX",           // 默认聚合类型
        FIELD_SDK_CONFIG_AD_TRACK: @(YES),              // 默认开启广告行为上报
        FIELD_SDK_CONFIG_AD_LOAD_TRACK: @(YES),         // 默认开启广告加载上报
        FIELD_SDK_CONFIG_FB_CTL: @"0;2;100",            // 默认FB控制参数
        FIELD_SDK_CONFIG_FB_LEVEL_EVENT: @""            // 默认无FB关卡事件
    };
    
    return [IMSDKStartupConfig configFromDictionary:defaultConfig];
}

/**
 * 从广告策略接口响应中更新策略数据
 * @param response 广告策略接口返回的响应数据
 */
- (void)updateStrategiesFromResponse:(IMAdStrategyResponse *)response {
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 开始从广告策略接口响应中更新策略数据"];
    
    // 调试日志：记录完整响应数据
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 完整响应数据调试 - response对象: %@", response];
    if (response) {
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 响应详情 - code: %ld, message: %@, data类型: %@", (long)response.code, response.message, NSStringFromClass([response.data class])];
        if (response.data && [response.data isKindOfClass:[NSArray class]]) {
            NSArray *dataArray = (NSArray *)response.data;
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 data数组长度: %lu", (unsigned long)dataArray.count];
            for (NSInteger i = 0; i < dataArray.count; i++) {
                NSDictionary *item = dataArray[i];
                if ([item isKindOfClass:[NSDictionary class]]) {
                    NSString *sceneName = item[@"scene_name"];
                    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 data[%ld] scene_name: %@, 完整内容: %@", (long)i, sceneName, item];
                }
            }
        }
    }
    
    if (!response) {
        [IMLogUtils error:IMLogTagGeneral format:@"[AdStrategyManager] 广告策略响应为空，无法更新策略数据"];
        return;
    }
    
    if (![response isSuccess]) {
        [IMLogUtils error:IMLogTagGeneral format:@"[AdStrategyManager] 广告策略接口调用失败，code: %ld, message: %@", (long)response.code, response.message];
        return;
    }
    
    if (!response.data || ![response.data isKindOfClass:[NSArray class]]) {
        [IMLogUtils error:IMLogTagGeneral format:@"[AdStrategyManager] 广告策略响应数据格式错误，data字段不是数组类型: %@", response.data];
        return;
    }
    
    NSArray *sceneStrategiesArray = response.data;
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 接收到 %lu 个场景策略数据", (unsigned long)sceneStrategiesArray.count];
    
    // 清空现有策略数据
    [self.sceneStrategies removeAllObjects];
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 已清空现有策略数据"];
    
    // 解析并存储新的策略数据
    NSInteger successCount = 0;
    for (NSInteger i = 0; i < sceneStrategiesArray.count; i++) {
        IMAdSceneStrategy *sceneStrategy = sceneStrategiesArray[i];
        if (![sceneStrategy isKindOfClass:[IMAdSceneStrategy class]]) {
            [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] 场景策略数据[%ld]不是IMAdSceneStrategy类型，跳过: %@", (long)i, sceneStrategy];
            continue;
        }
        
        // 调试日志：场景映射验证
        NSString *sceneName = sceneStrategy.scene_name;
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 处理场景[%ld]: scene_name=%@", (long)i, sceneName];
        
        // 验证场景映射
        IMAdScene mappedScene = [IMAdStrategyManager sceneFromName:sceneName];
        NSNumber *mappingResult = _sceneNameMapping[sceneName];
        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 场景映射验证 - 输入: %@, 映射结果: %@, 最终枚举值: %ld", sceneName, mappingResult, (long)mappedScene];
        
        if ([sceneName isEqualToString:@"SCENE_SDK_CONFIG"]) {
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 发现SDK配置场景，映射验证 - 期望枚举值: %ld, 实际枚举值: %ld", (long)IMAdSceneSDKConfig, (long)mappedScene];
        }
        
        // 根据scene_name映射到场景枚举
        IMAdScene scene = [IMAdStrategyManager sceneFromName:sceneStrategy.scene_name];
        self.sceneStrategies[@(scene)] = sceneStrategy;
        
        [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 成功加载场景策略[%ld]: %@ (%@) -> 场景枚举: %ld, 策略数量: %lu", 
         (long)i, sceneStrategy.scene_name, sceneStrategy.scene_desc, (long)scene, (unsigned long)sceneStrategy.strategy.count];
        
        // 特别记录SDK配置场景
        if (scene == IMAdSceneSDKConfig) {
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ 发现SDK配置场景策略: %@, 包含 %lu 个策略", 
             sceneStrategy.scene_name, (unsigned long)sceneStrategy.strategy.count];
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 SDK配置场景策略存储验证 - 键: %@, 值: %@", @(scene), sceneStrategy];
            
            // 立即验证存储结果
            IMAdSceneStrategy *storedStrategy = self.sceneStrategies[@(IMAdSceneSDKConfig)];
            [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 🔍 存储后立即验证 - 能否取回: %@", storedStrategy ? @"成功" : @"失败"];
            
            // 详细记录SDK配置场景的策略内容
            for (NSInteger j = 0; j < sceneStrategy.strategy.count; j++) {
                IMAdStrategy *strategy = sceneStrategy.strategy[j];
                if (strategy.ad_cond && strategy.ad_cond.additionalConditions) {
                    NSDictionary *additionalConditions = strategy.ad_cond.additionalConditions;
                    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] SDK配置策略[%ld] additionalConditions: %@", (long)j, additionalConditions];
                    
                    // 特别检查是否包含sdk_config_sdk_type
                    id sdkType = additionalConditions[FIELD_SDK_CONFIG_SDK_TYPE];
                    if (sdkType) {
                        [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] ✅ 在SDK配置策略[%ld]中找到sdk_config_sdk_type: %@", (long)j, sdkType];
                    }
                } else {
                    [IMLogUtils warning:IMLogTagGeneral format:@"[AdStrategyManager] SDK配置策略[%ld]缺少additionalConditions", (long)j];
                }
            }
        }
        
        successCount++;
    }
    
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 策略数据更新完成，成功加载 %ld/%lu 个场景策略", (long)successCount, (unsigned long)sceneStrategiesArray.count];
    [IMLogUtils info:IMLogTagGeneral format:@"[AdStrategyManager] 当前已加载的场景策略总数: %lu", (unsigned long)self.sceneStrategies.count];
    
    // 记录所有已加载的场景
    NSMutableArray *loadedScenes = [NSMutableArray array];
    for (NSNumber *sceneKey in self.sceneStrategies.allKeys) {
        IMAdSceneStrategy *strategy = self.sceneStrategies[sceneKey];
        [loadedScenes addObject:[NSString stringWithFormat:@"%@(%@)", strategy.scene_name, sceneKey]];
    }
    [IMLogUtils debug:IMLogTagGeneral format:@"[AdStrategyManager] 已加载的场景列表: %@", [loadedScenes componentsJoinedByString:@", "]];
}

@end
